﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using nRoute.Navigation.Mapping;
using nRoute.ViewModels;
using nRoute.Samples.Netflix.Data.Catalog;
using nRoute.Samples.Netflix.Data;
using nRoute.Components.Composition;
using System.Data.Services.Client;
using nRoute.Samples.Netflix.Views;
using nRoute.Components;

namespace nRoute.Samples.Netflix.ViewModels
{
    [DefineNavigationContent("Content/Netflix/Languages/", typeof(LanguagesListingView))]
    [MapViewModel(typeof(LanguagesListingView))]
    public class LanguagesListingViewModel
        : DataListingViewModelBase<Language, NetflixDataContext>
    {
        private ValueConverter<Language, DataServiceQuery<Title>> _converter;
            
        [ResolveConstructor]
        public LanguagesListingViewModel(NetflixDataContext context) : base(context) { }

        public ValueConverter<Language, DataServiceQuery<Title>> LanguageToTitleQueryConverter
        {
            get
            {
                if (_converter == null) _converter = CreateToTitleConverter();
                return _converter;
            }
        }

        protected override DataServiceQuery<Language> CreateQuery(string searchText)
        {
            var _query = base.Context.Languages.IncludeTotalCount();
            if (!string.IsNullOrWhiteSpace(searchText)) _query = (DataServiceQuery<Language>)_query.Where((l) => l.Name.IndexOf(searchText) != -1);
            return (DataServiceQuery<Language>)_query.OrderBy((g) => g.Name);
        }

        private ValueConverter<Language, DataServiceQuery<Title>> CreateToTitleConverter()
        {
            return new ValueConverter<Language, DataServiceQuery<Title>>((l) => (DataServiceQuery<Title>)(
                    from _l in base.Context.Languages.IncludeTotalCount()
                    from _t in _l.Titles
                    where _l.Name == l.Name
                    select _t));
        }
    }    
}